﻿using Furion.DatabaseAccessor;
using Furion.DependencyInjection;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Logging;
using Mrhd.Core.Entities;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace Mrhd.Application
{
    /// <summary>
    /// 账户服务
    /// </summary>
    public class AccountService : IAccountService, IScoped
    {
        private readonly IRepository<UserEntity> _repository;
        private readonly IRepository<UserMobileEntity> _mobileRepository;
        public AccountService(IRepository<UserEntity> repository,
            IRepository<UserMobileEntity> mobileRepository)
        {
            _repository = repository;
            _mobileRepository = mobileRepository;
        }

        public async Task<UserEntity> GetUserByUserNameAsync(string username)
        {
            return await _repository.SingleOrDefaultAsync(a => a.UserName == username, false);
        }

        public async Task<UserMobileEntity> GetUserByOpenIdAsync(string openid)
        {
            return await _mobileRepository.FirstOrDefaultAsync(a => a.OpenId == openid, false);
        }

        public async Task<UserMobileEntity> CreateUserAsync(string openid)
        {
            var entity = new UserMobileEntity { OpenId = openid, CreatedTime = DateTimeOffset.Now };
            await _mobileRepository.InsertAsync(entity);
            await _mobileRepository.SaveNowAsync();
            return entity;
        }

    }
}
